package org.spider.spiderweb.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {
    private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Bean
    RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        //序列化工具
        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //使用String可以不带双引号，但是不能直接序列化一个对象，只能直接序列化一个String类型
        RedisSerializer<String> stringRedisSerializer = RedisSerializer.string(); //UTF-8编码的序列化
        //key和hash使用String序列化
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        //value和hashValue使用json序列化
        template.setValueSerializer(stringRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);
        return template;
    }

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;

//    @Bean
//    public RedissonClient redissonClient() {
//        // 配置
//        Config config = new Config();
//        String url = String.format("redis://%s:%s", host, port);
//        if (StringUtils.isNotEmpty(password))
//            config.useSingleServer().setAddress(url).setPassword(password);
//        else
//            config.useSingleServer().setAddress(url);
//        logger.info("redisClient  url:{} ,password:{}", url, password);
//        // 创建RedissonClient对象
//        return Redisson.create(config);
//    }
}
